/*global $: true, setCookie: true, getCookie: true, escape: true, unescape: true */
var serverDate='';
var testCycle = '15';
 var _gaq = _gaq || [];

    (function() {
      var s, ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      try {
      	s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
//        alert('test:\t' + testCycle + '\ns:\t' + s);
      }
      catch(e) {
//	      alert('test:\t' + testCycle + '\nadd ga\nerror:\t' + e);
      }
    })();


function grabLeagueValue(urlPath){
	if(typeof(urlPath) === 'undefined')
	{
		return null;
	}
	
	var leagueValue, numPos = 2, urlList = urlPath.split('/');
	
	if( pageCheck(urlPath,false)){
		numPos=3;
	}
	
	leagueValue = urlList[numPos];
	//only for landing on /today/3 - there is no league data in uri
	if(typeof(leagueValue) === 'undefined' || leagueValue == ''){leagueValue = grabLeagueValue(getActiveLink());}
	
	return leagueValue;
}

function halftimeColumnUpdate(){
	
		$('.halftime-btn').unbind();
		$('.halftime-btn').bind('tap',function(){
			$(this).toggleClass('ui-btn-active-c');
			swapColumnDisplay();
		});
}

function getStringURL(pageEL){

	var stringURL;
	
	if(typeof(pageEL.attr('data-url')) !== 'undefined'){
		stringURL = pageEL.attr('data-url');
	}else{
		stringURL = getActiveLink();		
	}
	return stringURL;
}

function getActiveLink(){
	var activeURL = $('.main-sports-nav .ui-btn-active-c').attr('href');
	return activeURL;
}

function swapColumnDisplay(){
		$(".column-open").toggleClass('hide-column');
		$(".column-halftime").toggleClass('show-column');
}

/**
  *returns slug from array or true if slug is in url
  */
function pageCheck(url,returnDay){
	var i, activeURL = url, dirArray = ['today','yesterday','tomorrow','topten','thisweek','casino'];
	
	// check array for slugs that will need to keep history state
	for(i = 0; i < dirArray.length; i++){
		if(activeURL.indexOf(dirArray[i]) !== -1){
			if(returnDay){
				return dirArray[i];
			}else{
				return true;
			}	
		}
	}
}

function dateCheck(page,date,path){
	var feedDate, dateObj, currentSlug;

	if(date === ''){

		dateObj		= new Date();
		currentSlug	= pageCheck(path,true);
		if(currentSlug === 'today'){
			feedDate = String(dateObj.getFullYear()) + String($.sao.pad(dateObj.getMonth() + 1, 2)) + String($.sao.pad(dateObj.getDate(), 2)); // Today's date
		}else if(currentSlug === 'yesterday'){
			feedDate = String(dateObj.getFullYear()) + String($.sao.pad(dateObj.getMonth() + 1, 2)) + String($.sao.pad(dateObj.getDate()-1, 2));
		}else if(currentSlug === 'tomorrow'){
			feedDate = String(dateObj.getFullYear()) + String($.sao.pad(dateObj.getMonth() + 1, 2)) + String($.sao.pad(dateObj.getDate()+1, 2));
		}
	}else{
		
		//assigns date to data attribute for current page
		if(typeof(page.attr("data-date")) !== 'undefined'){
			feedDate = page.attr("data-date");
		}else{
			page.attr("data-date", date);
			feedDate = page.attr("data-date");
		}
	}
	
	return feedDate;
}

function historyCheck(){
	var i, urlList, leagueID, bpl;
	
	for(i=history.length; i>-1; i--){
		if(history[i].indexOf('#') !== -1){
			
			urlList = history[i].split('#');
			if(pageCheck(urlList[1],false)){
				leagueID = grabLeagueValue(urlList[1]);
				bpl = '/'+pageCheck(urlList[1],true)+'/3/'+leagueID;
				return bpl;
			}
		}
		
	}
}

function setBackBtnLink(urlPath){
	var backPageLink, leagueID = grabLeagueValue(urlPath);
	
	if(pageCheck(urlPath,false)){
		//for all other pages in pageCheck() array
		backPageLink = '/'+pageCheck(urlPath,true)+'/3/'+leagueID;
		setCookie('backLinkUrl',backPageLink,1);
	}
	
	if(typeof(backPageLink) === 'undefined'){
		//defualts to today when landing on a matchup page first
		backPageLink = getCookie('backLinkUrl',backPageLink,1);
		if(typeof(backPageLink) === 'undefined'){
			backPageLink = '/today/3/'+leagueID;
		}
	}
	
	//change hraf of all links with class
	$('.matchup-back-btn').attr('href', backPageLink);
}

function topTenHighlight(page){
	var urlPath = getStringURL(page),
		hrefVal = urlPath.replace('#',''),
		urlList = hrefVal.split('/');
	if(urlList[1] === 'topten'){
		$('.tab-nav-c a').removeClass('ui-btn-active-c');
		$('a[href="'+hrefVal+'"]').addClass('ui-btn-active-c');
	}
}

function runFeeds(urlPath, pageDate){

	var currentSlug, leagueID;
	
	//clear out all intervaled feed requests
	$.sao.emptyUpdaters();
	
	//if on correct page start feeds
	if(pageCheck(urlPath,false)){
	
		currentSlug = pageCheck(urlPath,true);
		leagueID = grabLeagueValue(urlPath);
		 
		if(currentSlug === 'today' || currentSlug === 'tomorrow'){
		
			if(pageDate !== ""){
				$.sao.updateGames({
					feed: 'odds',
					currentLeague: leagueID,
					feedParam: pageDate
				});
				$.sao.updateGames({
					feed: 'scores',
					feedParam:leagueID
				});
			}
			
		}
		else if(currentSlug === 'thisweek')
		{
		
			$.sao.updateGames({
				feed: 'football-odds',
				currentLeague: leagueID
			});
			$.sao.updateGames({
				feed: 'scores',
				feedParam:leagueID
			});
			
		}
	
	}
}

function keepHeaderFixed(){
	var agent=navigator.userAgent.toLowerCase();

	$(document).scroll(function() {
		var cHeader = $('.ui-column-header-c'),
			offset = cHeader.offset();

		if(offset.top > 285){
			cHeader.addClass('header-fix-position');

			if (agent.indexOf('iphone') >= 0){
				cHeader.css('top', offset.top );
			}
			
		}else{
			cHeader.removeClass('header-fix-position');
		}
	});
}

function setCookie(c_name,value,exdays){
	var c_value, exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	c_value=escape(value) + (isNaN(exdays) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name){
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++){
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x === c_name){
			return unescape(y);
		}
	 }
}


//run on the first time a page is created
$('.ui-page').live('pagecreate',function(event){
	var urlPath = getStringURL($(this));
	//for halftime-btn(s)
	halftimeColumnUpdate();
	
	//
	setBackBtnLink(urlPath);
	

	//$( ".day-selector" ).unbind();
	$( ".day-selector" ).bind( "change", function(event, ui) {
			$.mobile.changePage( $(this).val() );
	});

});

//run everytime a page is displayed
$('div').live('pageshow',function(event, ui){
	var message, urlPath = getStringURL($(this));	
	//var feedDate = dateCheck($(this),serverDate,urlPath);
	//
	topTenHighlight($(this));
	//
	runFeeds(urlPath,serverDate);
	/*
	if(pageCheck(urlPath,false)){
		keepHeaderFixed();
	}
	*/
	//clear off any hover classes that still may be on buttons
	$('.ui-btn-hover-c').removeClass('ui-btn-hover-c').addClass('ui-btn-up-c');
	

    try {
        _gaq.push(['_setAccount', 'UA-6441790-1']);

        hash = location.hash;

        if (hash) {
            _gaq.push(['_trackPageview', hash.substr(1)]);
        } else {
            _gaq.push(['_trackPageview']);
        }
//	message = 'test:\\t' + testCycle + '\\ntrack:\\t' + String(location) + '\\ngaq:\\t' + _gaq;
//	setTimeout("alert('" + message + "');", 2000);
    } catch(err) {
//      alert('test:\t' + testCycle + '\ntrack\nerror:\t' + err);
    }
	
	
});


$('div').live('pagebeforeshow',function(event, ui){
	if($('.day-selector')){
	$('.day-selector').unbind();
		$('.day-selector option[selected]').attr('selected', 'selected');
		$('.day-selector').selectmenu();
		$('.day-selector').selectmenu('refresh');
		$( ".day-selector" ).bind( "change", function(event, ui) {
			$.mobile.changePage( $(this).val() );
		});
	}
});

$(document).bind("mobileinit", function(){
	// Turn on page caching
	$.mobile.page.prototype.options.domCache = true;
	$.mobile.pushStateEnabled = true;
	$.mobile.touchOverflowEnabled = true;
	$.mobile.defaultPageTransition ='slide';
	
});
